const dayjs = require('@/utils/dayjs.min.js');
const BLE = require('@/utils/ble.js');
import store from "@/store";
// ArrayBuffer转16进度字符串
export function ab2hex (buffer) {
    var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (bit) {
        return ('00' + bit.toString(16)).slice(-2);
    });
    return hexArr.join('');
}
// JS根据传入日期算出当前周一到周日的日期数组
export function weekComputedfn  (day) {
    let utiljs = {};
    utiljs.weekComputedfn = {
        dates: [],
        formatDate: function (date) {
            var year = date.getFullYear() + '/';
            var month = (date.getMonth() + 1) + '/';
            var day = date.getDate();
            return year+month+day;
        },
        addDate: function (date, n) {
            date.setDate(date.getDate() + n);
            return date;
        },
        setDate: function (date) {
            let dates = [];
            var week = date.getDay() - 1;
            date = this.addDate(date, week * -1);
            // currentFirstDate = new Date(date);
            let weekObj = {
                0:'一',
                1:'二',
                2:'三',
                3:'四',
                4:'五',
                5:'六',
                6:'日',
            }
            for (var i = 0; i < 7; i++) {
                dates.push(this.formatDate(i == 0 ? date : this.addDate(date, 1)));
            }
            return dates.map((val,index)=>{
                return {
                    day:dayjs(val).format('DD'),
                    day2:val,
                    weekDay:weekObj[index],
                }
            });
        }
    }
    let date = day?day:dayjs().format('YYYY-MM-DD')
    //使用方法 utiljs.weekComputedfn.setDate(new Date())
    return utiljs.weekComputedfn.setDate(new Date(date))
}
// 16进制的字符串转换为整数
export function hex2int (hex) {
    var len = hex.length,
        a = new Array(len),
        code;
    for (var i = 0; i < len; i++) {
        code = hex.charCodeAt(i);
        if (48 <= code && code < 58) {
            code -= 48;
        } else {
            code = (code & 0xdf) - 65 + 10;
        }
        a[i] = code;
    }

    return a.reduce(function (acc, c) {
        acc = 16 * acc + c;
        return acc;
    }, 0);
}
// 16进度字符串转ArrayBuffer
export function hex2ab (hex) {
    if (hex.length % 2 != 0) {
        console.log('待转换字节数据长度应为偶数！！！');
        return null;
    }

    let buffer = new ArrayBuffer(hex.length / 2);
    let dataView = new DataView(buffer);

    for (var i = 0; i < hex.length / 2; i++) {
        dataView.setUint8(i, parseInt(hex.substring(i * 2, (i + 1) * 2), 16));
    }

    return buffer;
}
// 4字节十六进制转浮点数
export function hex2float (hexString, precision) {
    precision = parseInt(precision)
    if (isNaN(precision) || precision < 0) {
        precision = 2
    }

    // 高低位转换
    const byteArray = [];
    for (let i = 0; i < hexString.length; i += 2) {
        byteArray.unshift(hexString.substr(i, 2));
    }

    // 创建一个包含十六进制数的 ArrayBuffer
    const hexValue = '0x' + byteArray.join('');
    const buffer = new ArrayBuffer(4);
    const dataView = new DataView(buffer);
    dataView.setUint32(0, hexValue, false);

    // 从 DataView 中读取浮点数
    const floatValue = dataView.getFloat32(0, false);
    return floatValue.toFixed(precision);
}
// 字符串转16进制
export function stringToHex (str) {
    var result = '';
    for (var i = 0; i < str.length; i++) {
        result += str.charCodeAt(i).toString(16);
    }
    return result;
}
//  16进制转换字符串 // 0x00类型
export function hexToString (hex) {
    var rawString = "";
    for (var i = 0; i < hex.length; i += 2) {
        var code = parseInt(hex.substr(i, 2), 16);
        rawString += String.fromCharCode(code);
    }
    return rawString;
}
export function intHex2 (int) {
    let str = int.toString(16)
    if (str.length == 1) {
        str = '000' + str
    } else if (str.length == 2) {
        str = '00' + str
    } else if (str.length == 3) {
        str = '0' + str
    }
    return str
}
export function getItemColor (data) {
    if (data == 0) {
        return '#E5E5E5'
    } else if (data == 1) {
        return '#7CD37E'
    } else if (data == 2) {
        return '#78B2DD'
    } else if (data == 3) {
        return '#9C70DE'
    } else if (data == 4) {
        return '#FFA168'
    } else if (data == 5) {
        return '#F1C56B'
    }
}

// 获取电量对应icon路径
export function getBatteryIcon (data) {
    if (data > 0 && data <= 20) {
        return 'http://oss.antaimedical.com/images/static/2024/08/66c304f2e4b09217821c0fb2hdMHtlRfwMvK5ef66b1c62eaf87eb4686a697559b4b2.png'
    } else if (data > 20 && data <= 40) {
        return 'http://oss.antaimedical.com/images/static/2024/08/66c30502e4b09217821c0fb38dZsR6ueVlW10f0d237ddaa9c203d49088b73b3e2094.png'
    } else if (data > 40 && data <= 60) {
        return 'http://oss.antaimedical.com/images/static/2024/08/66c30510e4b000d2c606b52fx6wUcraql9JJf6c4e3ebb6ae6f8af288262b54b6452a.png'
    } else if (data > 60 && data <= 80) {
        return 'http://oss.antaimedical.com/images/static/2024/08/66c3051ce4b000d2c606b530GeP6gHwOi0x9fb8fabe44c7f9e04db5027952af17a2c.png'
    } else if (data > 80 && data <= 100) {
        return 'http://oss.antaimedical.com/images/static/2024/08/66c30526e4b09217821c0fb4bKcQ4BHBF8a3d526d13b0335066752a5bdbedc4633c1.png'
    } else {
        return ''
    }
}

// 获取某天所在的周日期
export function getWeekDate (date) {
    let start
    let end
    if (date) {
        start = dayjs(dayjs(date).startOf('week')).format('YYYY/MM/DD')
        end = dayjs(dayjs(date).endOf('week')).format('YYYY/MM/DD')
    } else {
        start = dayjs(dayjs().startOf('week')).format('YYYY/MM/DD')
        end = dayjs(dayjs().endOf('week')).format('YYYY/MM/DD')
    }
    start = dayjs(dayjs(start).add(1, 'day')).format('YYYY/MM/DD')
    end = dayjs(dayjs(end).add(1, 'day')).format('YYYY/MM/DD')
    end = end.split('/')
    end.splice(0, 1)
    end = end.join('/')
    return `${start}-${end}`
}

// 乘法运算
export function multiply (a, b) {
    const precision = getPrecision(a) + getPrecision(b);
    const multiplier = Math.pow(10, precision);
    return (Math.round(a * multiplier) * Math.round(b * multiplier)) / (multiplier * multiplier);
}

// 获取浮点数的小数位数
export function getPrecision (num) {
    const str = String(num);
    const decimalIndex = str.indexOf('.');
    return decimalIndex === -1 ? 0 : str.length - decimalIndex - 1;
}
/**
 * @param {Object} obj
 * @param {Function} fn
 */
export function mergeObjOfValue (tarObj, obj) {
    for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(tarObj, key) === true) {
            tarObj[key] = obj[key]
        }
    }
}
// 整数转4位数16进制 例子1转换0001
export function toHex4 (num) {
    let hex = num.toString(16);
    return hex.padStart(4, '0');
}

export function crc16 (data) {
    let arr = data.match(/.{1,2}/g).map((value) => '0x' + value)
    let crc = 0xFFFF;
    let odd;
    for (let i = 0; i < arr.length; i++) {
        crc = crc ^ arr[i];
        for (let j = 0; j < 8; j++) {
            odd = crc & 0x0001;
            crc = crc >> 1;
            if (odd) {
                crc = crc ^ 0x8005;
            }
        }
    }
    return (crc & 0xFFFF).toString(16).padStart(4, '0'); // Convert to hex and pad to 4 digits
}
// 使用示例
// const data = [0xaa, 0x55, 0x00, 0x02,0x00,0x01,0x00,0x04,0x10,0x00,0x00,0x00]; // 需要计算CRC的数据
// const data = aa5500002; // 需要计算CRC的数据
// const result = crc16(data); // 计算CRC
// console.log('CRC16 result:', result); // 显示结果
// 16进制转换浮点数 8字节
export function hexStringToFloat (hexString) {
    // 将16进制字符串转换为10进制整数
    const intValue = parseInt(hexString, 16);
    // 将10进制整数转换为32位浮点数
    const floatValue = new Float32Array(new Int32Array([intValue]).buffer)[0];
    return floatValue;
}

// 嵌入式返回内容转换
export function formReceiveData (str, type) {
    // let str = 'aa5580010001000238010f4b'
    // aa55 8001 0001 0002 3801 0f4b
    let str1 = str.substring(0, 12); //固定标识
    let str2 = str.substring(12, 16);//内容长度字符判断
    let str3 = str.substring(16, str.length - 4);//内容
    let str4 = str.substring(str.length - 4, str.length);//crc检验码
    let contentArr = []
    if (type == 'crc16') { // 000d，000e命令码 逻辑
        contentArr = str3.match(/.{1,8}/g) || [];
        contentArr = contentArr.map((v) => {
            let arr = v.match(/.{1,2}/g) || []
            let vStr = arr[3] + arr[2] + arr[1] + arr[0]
            return hexStringToFloat(vStr).toFixed(2) + ''
        })
    }
    else if (type == '0001') {
        contentArr = str3.match(/.{1,2}/g) || [];;
        contentArr = contentArr.map((v, index) => {
            if (index <= 2) {
                return hex2int(v) + ''
            } else {
                return hexToString(v)
            }
        })
    }
    else if (type == '000f') {
        let fArr = str3.match(/.{1,2}/g) || [];;
        let fwVersion = '' //版本号
        contentArr.push(hex2int(fArr[0]) + '')
        fArr.forEach((v, index) => {
            if(index>=1&&index<=12){
                fwVersion = fwVersion+hexToString(v)
            }
        })
        if(contentArr[0] == 1){
            contentArr.push(fwVersion.replace(/\u0000/g, ''))
            contentArr.push(hex2int(fArr[13]+fArr[14])+'')
        }
    }
    else if (type == '0009') {
        contentArr = [hex2int(str3.substring(0,2))+'',hex2int(str3.substring(2,6))+'']
    }
    else {
        contentArr = str3.match(/.{1,2}/g) || [];;
        contentArr = contentArr.map((v) => {
            return hex2int(v) + ''
        })
    }
    return contentArr
}
// 请求嵌入式
export function bleHttp (url, params) {
    // runCode:流水号，数字类型
    // lengthCode:数据长度，数字类型
    // type: 返回数据处理格式， crc16
    // contentCode: 数据内容
    let httpUrl = url
    if (params.runCode) {  // 000d，000e命令码 逻辑
        let runCode = toHex4(params.runCode)
        let lengthCode = params.lengthCode ? toHex4(params.lengthCode) : '0001'
        let contentCode = toHex4(params.contentCode)
        let str = url + runCode + lengthCode + contentCode
        httpUrl = str + crc16(str)
    }
    if (params.type == '0009') {
        let HwVersion = stringToHex(params.HwVersion)
        let FwVersion = stringToHex(params.FwVersion)
        let ImageSize = parseInt(params.ImageSize).toString(16)
        if (HwVersion.length != 8) {
            for (let index = HwVersion.length; index < 8; index++) {
                HwVersion += '0'
            }
        }
        if (FwVersion.length != 24) {
            for (let index = FwVersion.length; index < 24; index++) {
                FwVersion += '0'
            }
        }
        if (ImageSize.length != 8) {
            for (let index = ImageSize.length; index < 8; index++) {
                ImageSize = '0' + ImageSize
            }
        }
        let contentCode = toHex4(params.FwId) + HwVersion + FwVersion + ImageSize + toHex4(params.ImageCRC)
        let str = url + contentCode
        httpUrl = str + crc16(str)
    }
    return new Promise((resolve, reject) => {
        if (store.state.ble.state == 0) {
            BLE.common.setRequest(httpUrl)
        } else {
            reject(store.state.ble.state)
        }
        uni.$once('response', (res) => {
            // 获取命令码
            let commandCode = res.substring(0, 8) 
            // 获取流水号
            let runCode = res.substring(8, 12) 
            if (commandCode.indexOf(params.key) > -1) {
                let resData = {
                    runCode:hex2int(runCode),
                    code:commandCode,
                    data:formReceiveData(res,params.type)
                }
                console.log("%c Line:310 🍢 res", "color:#fca650", JSON.stringify(resData));
                resolve(resData)
            }
        })
    })
}

